package fragments;


import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.administrator.baseproject.BaseFragment;
import com.example.administrator.newxlmedical.R;
import com.irisian.irissdk.IrisSdk;

import java.util.ArrayList;

import beans.NewUserInfoBean;
import beans.PostBean;
import beans.PutAndDeleteBean;
import beans.RegisterInfoBean;
import beans.UserInfoBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import netframe.GetRetrofit;
import netframe.NetAddress;
import register.IrisRegisterClass;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import singleton.SingletonClass;
import utils.FormateUtils;
import utils.MediaPlayerUtils;
import utils.TimeUtil;
import utils.ToastUtil;

/**
 * A simple {@link Fragment} subclass.
 */
public class HospitalIrisRegisterFragment extends BaseFragment {

    @BindView(R.id.iv_hospital_iris_rigister_back)
    ImageView ivBack;
    Unbinder unbinder;
    private IrisRegisterClass irisRegister;

    private MediaPlayer mediaPlayer;
    private RegisterInfoBean bean;
    private MyHandler allHandler;

    public HospitalIrisRegisterFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_iris_register, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initView() {
        super.initView();
        allHandler = SingletonClass.getSingleton(MyHandler.class);
        bean = (RegisterInfoBean) getArguments().getSerializable(Constants.BASE_IRIS_REGISTER_FRAGMENT);
        irisRegister = new IrisRegisterClass(mContext) {
            @Override
            public void irisNetWork(String image) {
//                getIris(image);
                if (bean.isOneFingerprintRegister()) {
                    Log.e(TAG, "irisNetWork: " );
                    updateUserInfo("set LeftImg = '" + image + "',ChangeTime = '" + TimeUtil.getMillisecondDate() + "', RightImg = '" + image + "', UserType =1, RoleInfoId = " + bean.getRegisterRole() + " where UCode = '" + bean.getCode() + "'");
                } else {
                    postUserInfo(image);

                }
            }

            @Override
            public void irisFailure() {
                Message message = allHandler.obtainMessage();
                message.what = HandlerConstant.REGISTER_FAILURE;
                message.obj = bean;
                allHandler.sendMessage(message);
            }
        };
    }

    void postUserInfo(String image) {
        UserInfoBean userInfoBean = new UserInfoBean();
        userInfoBean.setName(bean.getName());
        userInfoBean.setUCode(bean.getCode());
        userInfoBean.setSubTime(TimeUtil.getMillisecondDate());
        userInfoBean.setDepartment(bean.getDepartment());
        userInfoBean.setRoleInfoId(bean.getRegisterRole());
        if (!TextUtils.isEmpty(bean.getPassword())) {
            userInfoBean.setPassword(bean.getPassword());
        }
        userInfoBean.setLeftImg(image);
        userInfoBean.setRightImg(image);
        userInfoBean.setWorkKind(bean.getWorkKind());
        userInfoBean.setEnable(true);
        userInfoBean.setChangeTime(TimeUtil.getMillisecondDate());

        Call<PostBean> call = GetRetrofit.getInstance().postUserInfo(NetAddress.token, NetAddress.machineCode, userInfoBean);
        call.enqueue(new Callback<PostBean>() {
                         @Override
                         public void onResponse(Call<PostBean> call, Response<PostBean> response) {
                             PostBean body = response.body();
                             if (body != null && body.getId() > 0) {
                                 irisRegister.releaseIris();
//                                 mediaPlayer = MediaPlayer.create(mContext, R.raw.register_success);
//                                 mediaPlayer.start();
//                                 allHandler.sendEmptyMessage(HandlerConstant.REGISTER_SUCCESS);
                                 getUserInfoId("select * from UserInfo where UCode = '" + bean.getCode() + "'");
                             }
                         }

                         @Override
                         public void onFailure(Call<PostBean> call, Throwable t) {
                             irisRegister.releaseIris();
                         }
                     }

        );
    }

    private void updateUserInfo(String sql) {
        Call<PutAndDeleteBean> call = GetRetrofit.getInstance().postUserInfo(NetAddress.token, NetAddress.machineCode, sql);
        call.enqueue(new Callback<PutAndDeleteBean>() {
            @Override
            public void onResponse(Call<PutAndDeleteBean> call, Response<PutAndDeleteBean> response) {
                PutAndDeleteBean body = response.body();
                if (body != null && body.getAffectRowCount() > 0) {
                    IrisSdk.stopReadDistance(mContext);
                    IrisSdk.closeCamera(mContext);
                    getUserInfoId("select * from UserInfo where UCode = '" + bean.getCode() + "'");
                }
            }

            @Override
            public void onFailure(Call<PutAndDeleteBean> call, Throwable t) {

            }
        });
    }

    private void getUserInfoId(String sql) {
        GetRetrofit.getInstance().getUserInfo2(NetAddress.token, NetAddress.machineCode, sql).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<NewUserInfoBean>() {
            @Override
            public void call(NewUserInfoBean userInfoBean) {
//                int userInfoId;
//                if (!bean.isOneFingerprintRegister()) {
                int userInfoId = userInfoBean.getData().get(0).getID();
                setFingerprintId("set FingerprintId = " + (10000 - userInfoId) + " where ID = " + userInfoId);
//                } else {
//                    userInfoId = userInfoBean.getData().get(0).getFingerprintId();
//                }
//                if (userInfoId > 0) {
//                    Message message = allHandler.obtainMessage();
//                    message.obj = fingerprintUserId;
//                    message.what = HandlerConstant.DELETE_FINGERPRINT_USER;
//                    allHandler.sendMessage(message);
//                }
            }
        });
    }

    //设置第二个指纹的ID
    public void setFingerprintId(String sql) {
        Call<PutAndDeleteBean> call = GetRetrofit.getInstance().putUserInfo(NetAddress.token, NetAddress.machineCode, sql);
        call.enqueue(new Callback<PutAndDeleteBean>() {
            @Override
            public void onResponse(Call<PutAndDeleteBean> call, Response<PutAndDeleteBean> response) {
                registerSuccess();
            }

            @Override
            public void onFailure(Call<PutAndDeleteBean> call, Throwable t) {

            }
        });
    }

    private void registerSuccess() {
        MediaPlayerUtils.playSound(mContext,R.raw.register_success);
        bean.setPut(true);
        Message message = allHandler.obtainMessage();
        message.what = HandlerConstant.REGISTER_SUCCESS;
        message.obj = bean;
        allHandler.sendMessage(message);

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.iv_hospital_iris_rigister_back)
    public void onViewClicked() {
        irisRegister.releaseIris();
        Message message = allHandler.obtainMessage();
        message.what = HandlerConstant.REGISTER_TYPE;
        message.obj = bean;
        allHandler.sendMessage(message);
    }
}
